import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2022-11-10
 * Time:10:03
 */

public class SingleLinkedList {
    class ListNode{
        int val;
        ListNode next;
        public ListNode(int val){
            this.val=val;
        }
    }
    ListNode head;
    //头插法
    public void addFirst(int data){
        ListNode node=new ListNode(data);
        node.next=head;
        head=node;
    }
    //尾插法
    public void addLast(int data){
        ListNode listNode=new ListNode(data);
        if(head==null){
            head=listNode;
            return;
        }
        ListNode cur=head;
        while(cur.next!=null){
            cur=cur.next;
        }
        cur.next=listNode;
    }
    //任意位置插入,第一个数据节点为0号下标
    public boolean addIndex(int index,int data){
        //判断合法性
        if(index<0||index>size()-1){
            System.out.println("超出范围");
            return false;
        }
        //插入
        int i=0;
        ListNode cur=head;
        ListNode node =new ListNode(data);
        while(i<index){
            i++;
            cur=cur.next;
        }
        node.next=cur.next;
        cur.next=node;
        return true;
    }
    //查找是否包含关键字key是否在单链表当中
    public boolean contains(int key){
        ListNode cur=head;
        while(cur!=null){
            if(cur.val==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }
    //删除第一次出现关键字为key的节点
    public void remove(int key){
        if(head.val==key){
            head=head.next;
            return;
        }
        ListNode cur=head;
        ListNode pre=cur;
        while(cur!=null){
            if(cur.val==key){
                pre.next=cur.next;
                return;
            }
            pre=cur;
            cur=cur.next;
        }
        System.out.println("没有这个值");
    }
    //删除所有值为key的节点
    public void removeAllKey(int key){
        while(head.val==key){
            head=head.next;
        }
        ListNode cur=head;
        ListNode pre=cur;
        while(cur!=null){
            if(cur.val==key){
                pre.next=cur.next;
                cur=cur.next;
            }else {
                pre=cur;
                cur=cur.next;
            }
        }
    }
    //得到单链表的长度
    public int size(){
        ListNode node=head;
        int sum=0;
        while(head!=null){
            head=head.next;
            sum++;
        }
        return sum;
    }
    public void display(){
        ListNode cur=head;
        System.out.print("[");
        while(cur.next!=null) {
            System.out.print(cur.val+",");
            cur=cur.next;
        }
        System.out.print(cur.val+"]");
    }
    public void clear(){
        head=null;
    }
}
